﻿using System;
using System.Collections.ObjectModel;

using GuidGen.Contracts;
using GuidGen.Input;
using GuidGen.Models;

namespace GuidGen.ViewModels
{
    public class MainViewModel : ViewModelBase
    {
        private GeneratedGuid _currentGuid;
        private readonly IDateTimeService _dateTimeService;
        private readonly IClipboard _clipboard;
        private readonly IGuidGenerator _guidGenerator;

        public DelegateCommand GenerateGuid { get; private set; }
        public DelegateCommand ItemDoubleClick { get; private set; }

        public GeneratedGuid CurrentGuid
        {
            get { return _currentGuid; }
            private set
            {
                if (_currentGuid == value) return;
                _currentGuid = value;
                NotifyPropertyChanged();
            }
        }

        public ObservableCollection<GeneratedGuid> LastGuids { get; private set; }

        public MainViewModel(IDateTimeService dateTimeService, IClipboard clipboard, IGuidGenerator guidGenerator)
        {
            if (dateTimeService == null) throw new ArgumentNullException("dateTimeService");
            if (clipboard == null) throw new ArgumentNullException("clipboard");
            if (guidGenerator == null) throw new ArgumentNullException("guidGenerator");
            _dateTimeService = dateTimeService;
            _clipboard = clipboard;
            _guidGenerator = guidGenerator;
            GenerateGuid = new DelegateCommand(OnGenerateGuid);
            ItemDoubleClick = new DelegateCommand(OnItemDoubleClick);
            LastGuids = new ObservableCollection<GeneratedGuid>();
            GenerateGuid.Execute(null);
        }

        private void OnItemDoubleClick(object obj)
        {
            if (obj == null) return;
            var guid = (GeneratedGuid)obj;
            CopyToClipboard(guid.Guid);
        }

        private void OnGenerateGuid(object obj)
        {
            var guid = _guidGenerator.GenerateGuid();
            var oldGuid = CurrentGuid;
            CurrentGuid = new GeneratedGuid(guid, _dateTimeService.Now);

            CopyToClipboard(guid);

            if (oldGuid != null)
            {
                LastGuids.Add(oldGuid);
            }
        }

        private void CopyToClipboard(Guid guid)
        {
            _clipboard.SetText(guid.ToString());
        }
    }
}